import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:namewava/jc_rote_path.dart';
import 'package:namewava/pages/dice/widgets/jc_dice_loading.dart';
import 'package:namewava/pages/dice/widgets/jc_dice_normal.dart';
import 'package:namewava/pages/dice/widgets/jc_dice_problem.dart';
import 'package:namewava/pages/dice/widgets/jc_dice_result.dart';
import 'package:namewava/utils/jc_cache.dart';
// import 'package:namewava/utils/jc_global.dart';
import 'package:namewava/utils/jc_image_path.dart';
import 'package:namewava/utils/jc_screenutil_info.dart';
import 'package:namewava/utils/js_request.dart';
import 'package:notification_centre/notification_centre.dart';

class JcDice extends StatefulWidget {
  const JcDice({super.key});

  @override
  State<JcDice> createState() => _JcDiceState();
}

class _JcDiceState extends State<JcDice> with AutomaticKeepAliveClientMixin {
  ///0初始状态 1问题状态 2生成状态 3生成完成
  RxInt step = 0.obs;
  RxBool isFinshed = false.obs;
  Map problemDic = {
    'interests': '',
    'traits': '',
    'networkName': '',
    'particularlyName': '',
    'longName': ''
  };
  RxInt myCoins = 0.obs;
  RxInt maxFreeCount = 5.obs;
  RxString roundomName = ''.obs;
  _appIsLogin() {
    var login = JcCache.getInstance().get('wavaIsLogin');
    if (login is bool && login) {
      var wavaNameRecord = JcCache.getInstance().get('wavaNameRecord');
      var wavaUserId = JcCache.getInstance().get('wavaUserId');
      //  String recordNames = '';
      int maxFree = 5;
      if (wavaNameRecord == null) {
      } else {
        wavaNameRecord = jsonDecode(wavaNameRecord);
        for (var element in wavaNameRecord) {
          var userId = element['userId'];
          if (wavaUserId == userId) {
            maxFree--;
          }
        }
      }
      maxFreeCount.value = maxFree;
      JsRequest.homeRequest(success: (res) {
        myCoins.value = res['availableCoins'];
        isFinshed.value = true;
        step.value = 0;
        problemDic = {
          'interests': '',
          'traits': '',
          'networkName': '',
          'particularlyName': '',
          'longName': ''
        };
      });
    } else {
      Get.toNamed(JcRotePath.jcLogin);
    }
  }

  @override
  void initState() {
    super.initState();
    print('JcDice-initState');
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _appIsLogin();
    });
    NotificationCenter().addObserver('wavaLoninEvents', this, (r) {
      if (mounted) {
        _appIsLogin();
      }
    });
    NotificationCenter().addObserver('coinChange', this, (res) {
      if (mounted) {
        _appIsLogin();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    NotificationCenter().removeObserver('wavaLoninEvents', this);
    NotificationCenter().removeObserver('coinChange', this);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: null,
      body: Container(
        height: JcScreenutilInfo.screenHeight,
        width: JcScreenutilInfo.screenWidth,
        decoration: const BoxDecoration(
            image: DecorationImage(
                image: AssetImage(JcImagePath.jcDiceBg), fit: BoxFit.fill)),
        child: SingleChildScrollView(
          child: Obx(() {
            return isFinshed.value
                ? Column(
                    children: [
                      SizedBox(
                        height: 40.h,
                      ),
                      Image.asset(JcImagePath.jcDiceIcon),
                      Obx(() {
                        if (step.value == 0) {
                          return JcDiceNormal(
                            diceTap: () {
                              print('下一步');
                              step.value = 1;
                            },
                          );
                        } else if (step.value == 1) {
                          return JcDiceProblem(
                            nextTap: (p) {
                              problemDic = p;
                              maxFreeCount.value = maxFreeCount.value - 1;
                              print('下一步');
                              step.value = 2;
                            },
                            p: problemDic,
                            freeCount: maxFreeCount.value,
                            myCoins: myCoins.value,
                          );
                        } else if (step.value == 2) {
                          return JcDiceLoading(
                            backTap: () {
                              step.value = 1;
                            },
                            nextTap: (name) {
                              roundomName.value = name;
                              step.value = 3;
                            },
                          );
                        } else {
                          return JcDiceResult(
                            dismissEvents: () {
                              _appIsLogin();
                              step.value = 0;
                            },
                            name: roundomName.value,
                          );
                        }
                      })
                    ],
                  )
                : const Text('');
          }),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
